package org.study.stream;

import lombok.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

/**
 * 参考 https://www.jb51.net/article/218287.htm
 *
 * @author Administrator
 * @date 2022-12-27
 */
public class StreamTest04 {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>(10000);
        List<Integer> list2 = new ArrayList<>(10000);
        List<Integer> list3 = new ArrayList<>(10000);
        Lock lock = new ReentrantLock();
        IntStream.range(0, 10000).forEach(list1::add);
        IntStream.range(0, 10000).parallel().forEach(list2::add);
        IntStream.range(0, 10000).parallel().forEach(i -> {
            lock.lock();
            try {
                list3.add(i);
            } finally {
                lock.unlock();
            }
        });
        System.out.println("串行执行的大小：" + list1.size());
        System.out.println("并行执行的大小：" + list2.size());
        System.out.println("加锁并行执行的大小：" + list3.size());

        List<Person> persons = new ArrayList<>();
        for (int i = 0; i < 500; i++) {
            Person p = new Person(i, "name-" + i, "sex-" + i, i);
            persons.add(p);
        }
        doFor(persons);
        doStream(persons);
        doParallelStream(persons);
    }

    private static void doFor(List<Person> persons) {
        long start = System.currentTimeMillis();
        for (Person person : persons) {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("使用 for() 耗时：" + (System.currentTimeMillis() - start));
    }

    private static void doStream(List<Person> persons) {
        long start = System.currentTimeMillis();
        persons.stream().forEach(person -> {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("使用 stream() 耗时：" + (System.currentTimeMillis() - start));
    }

    private static void doParallelStream(List<Person> persons) {
        long start = System.currentTimeMillis();
        persons.parallelStream().forEach(person -> {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("使用 parallelStream() 耗时：" + (System.currentTimeMillis() - start));
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class Person {
        int id;
        String name;
        String sex;
        float height;
    }
}

